<template>
  <div class="mobilelogin">
    <h1>手机号登录</h1>
    <template>
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="ruleForm.mobile"></el-input>
        </el-form-item>

        <el-form-item label="验证码" prop="mobilecode">
          <el-input v-model="ruleForm.mobilecode"></el-input>
          <span class="mobilecode" @click="getMobileCodeFn">获取验证码</span>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">
            提交
          </el-button>
        </el-form-item>
      </el-form>
    </template>
  </div>
</template>

<script>
import * as api from "@/api/login";
export default {
  data() {
    //验证手机号
    let checkMobile = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入手机号！"));
      } else if (!/^1\d{10}$/.exec(value)) {
        return callback(new Error("请输入11位的手机号！"));
      } else {
        return callback();
      }
    };
    //验证手机验证码
    let checkMobilecode = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入密码！"));
      } else {
        return callback();
      }
    };

    return {
      ruleForm: {
        mobile: "",
        mobilecode: "",
      },
      rules: {
        mobile: [{ validator: checkMobile, trigger: "blur" }],
        mobilecode: [{ validator: checkMobilecode, trigger: "blur" }],
      },
    };
  },
  methods: {
    getMobileCodeFn() {
      if (this.ruleForm.mobile) {
        api.getMobileCode(this.ruleForm.mobile).then((res) => {
          console.log(res);
        });
      } else {
        alert("请输入手机号");
      }
    },

    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // alert("submit!");
          console.log(this.ruleForm.mobilecode);
          let rs = await api.mobileLogin(this.ruleForm.mobilecode);
          console.log(rs);
          if (rs.data.state) {
            this.jumpFn("/layout");
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss">
.mobilecode {
  position: absolute;
  right: 10px;
}
</style>
